package com.spboot.exts.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.validation.constraints.Positive;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.spboot.exts.entity.News;
import com.spboot.exts.entity.util.PageInfo;
import com.spboot.exts.service.NewsService;

@Controller
@RequestMapping("/news")
public class NewsController {

	@Autowired
	NewsService newsService;

	@RequestMapping("/list")
	public String list(
			Model model ,
			@RequestParam(defaultValue = "1", required = false) Integer pageno, String title) {
		PageInfo<News> pageInfo = newsService.selectNews(pageno, title);
		model.addAttribute("pageInfo", pageInfo);
		return "news_list";
	}
	
	@GetMapping("toadd")
	public String toAdd(){
		return "news_add";
	}
	
	@PostMapping("add")
	public String add(News news,Model model){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
		news.setCreateTime(sdf.format(new Date()));
		
		boolean f = newsService.addNews(news);
		
		if(f){
			return "redirect:list";
		}
		model.addAttribute("error", "添加新闻失败");
		return "news_add";
	}
}
